import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

//自定义hook 必须use开头 小驼峰
//泛型约束 约束stateName 必须是RootState的键
export function useInitialState<T extends keyof RootState>(
  action: () => void,
  stateName: T
) {
  const dispatch = useDispatch()
  const InitState = useSelector((state: RootState) => state[stateName])

  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  return InitState
}
